function loglik = llfpermtempdecompdiff(y,params,init_V,gainvector);
%this create the log likelihood for the following model.
%   x(t+1) = A*x(t) + w(t),  w ~ N(0, Q),  x(0) ~ N(init_x, init_V)
%   y(t)   = C*x(t) + v(t),  v ~ N(0, R)

% state(t) = T*state(t-1) + err1(t), Eerr1(t)*err1(t)'=Q
% data(t) = Z*state(t) + err2(t), Eerr2(t)*err2(t)'=H


%x(t) is a vector
%muc
%Phit 
%chit

%where muc is a constant.  hence Q(1,1) = 0;
%the rest of Q is a diagonal.
%Phit  is a random walk with drift muc
%Chit is an AR(1) with persistence defined by A(3,3)

if nargin < 4;
    gainvector = [];
end


if length(params) == 3;
    params = [0  params];
end

muc = params(1);
rho_temp = params(2);
sigperm = params(3);
sigtemp = params(4);
if length(params) == 5;
    error('broke this');
  theta_perm = params(5);
      sigmeaserr = 0;
else
      theta_perm =0;
    sigmeaserr = 0;
end

% init_x = [muc 1*mean(y(1:20)) 0*mean(y(1:20))]';
init_x = [muc 0 0 muc 0 0]';

if nargin == 2;
init_V = diag([0  sigperm  sigtemp./sqrt(1-rho_temp^2)  0  sigperm  sigtemp./sqrt(1-rho_temp^2)].^2); 
%     init_V =  diag([0  (sigperm^2)./(1-theta_perm^2)  sigtemp./sqrt(1-rho_temp^2) 0  (sigperm^2)./(1-theta_perm^2)  sigtemp./sqrt(1-rho_temp^2)].^2);
     init_V(3,6) = rho_temp*(sigtemp^2)./(1-rho_temp^2);
    init_V(6,3) = rho_temp*(sigtemp^2)./(1-rho_temp^2);
 
  %  init_V(2,4) = theta_perm*(sigperm^2)./(1-theta_perm^2);
  %  init_V(4,2) = theta_perm*(sigperm^2)./(1-theta_perm^2);
 
     
elseif isempty(init_V)
    init_V = diag([0  sigperm  sigtemp./sqrt(1-rho_temp^2)  0  sigperm  sigtemp./sqrt(1-rho_temp^2)].^2);
    %     init_V =  diag([0  (sigperm^2)./(1-theta_perm^2)  sigtemp./sqrt(1-rho_temp^2) 0  (sigperm^2)./(1-theta_perm^2)  sigtemp./sqrt(1-rho_temp^2)].^2);
    init_V(3,6) = rho_temp*(sigtemp^2)./(1-rho_temp^2);
    init_V(6,3) = rho_temp*(sigtemp^2)./(1-rho_temp^2);


end


    
A = zeros(6,6);
A(1,1) = 1;
A(3,3) = rho_temp;
A(4,1) =    1;
A(6,3) =   1; 
A(2,2) = theta_perm;
A(5,2) =   1; 

Q = diag([0 sigperm sigtemp 0 0 0].^2);
R = sigmeaserr^2;
C = [1 1 1 0 0 -1];

% 
% size(y)
% size(A)
% size(C)
% size(Q)
% size(R)
% size(init_x)
% size(init_V)
% A
% C
if isempty(gainvector)
    [loglik] = mykalman(y,A,C,Q,R,init_x,init_V,0);
else
    [loglik] = mykalmanwithgain(y,A,C,Q,R,init_x,init_V,0,gainvector);
end

loglik = -1*loglik;

